<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Models\Site;
use Illuminate\Http\Request;
use Auth;
use App\Http\Resources\SiteResource;
use App\Http\Requests\SiteRequest;
use App\Http\Resources\ModuleResource;
use ModuleService;
use PermissionService;

/**
 * 站点
 * @package App\Api
 */
class SiteController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:sanctum')->except(['current']);
        $this->authorizeResource(Site::class, 'site');
        $this->middleware(['site'])->only(['current']);
    }

    public function current()
    {
        return new SiteResource(site());
    }



    /**
     * 站点列表
     * @return void
     */
    public function index()
    {
        $sites = Auth::user()->sites->load('master.group.packages');
        return SiteResource::collection($sites);
    }

    /**
     * 新增站点
     * @param Request $request
     * @return void
     */
    public function store(SiteRequest $request, Site $site)
    {
        $site->fill($request->input());
        $site->user_id = Auth::id();
        $site->config = [];
        $site->save();
        return $this->message('站点添加成功');
    }

    /**
     * 显示某一个站点
     *
     * @param Site $site
     * @return void
     */
    public function show(Site $site)
    {
        return new SiteResource($site);
    }

    /**
     * 更新站点
     * @param Request $request
     * @param Site $site
     * @return void
     */
    public function update(Request $request, Site $site)
    {
        $site->fill($request->input())->save();
        return ['message' => '修改成功'];
    }

    /**
     * 删除
     * @param Site $site
     * @return void
     */
    public function destroy(Site $site)
    {
        $site->delete();
        return ['message' => '删除成功'];
    }

    public function permission(Site $site)
    {
        PermissionService::updateSitePermission($site);
        return $this->message('权限表更新成功');
    }
}
